<template>
	<div class="register">
		<div class="register-container">
			<div class="register-header">
				<div class="register-header-title">新用户注册</div>
				<p class="register-header-info">很高兴您将成为商城的会员（注册只需一步）</p>
			</div>
			<my-input
					type="tel"
					icon="icon-mobile"
					v-model="form.mobile"
					:required="true"
					placeholder="手机号"
					:rules="rules.mobile"
			/>
			<my-input
					type="password"
					v-model="form.pwd"
					placeholder="密码"
					:required="true"
					:rules="rules.pwd"
			/>
			<my-input
					type="password"
					v-model="form.pwd2"
					:required="true"
					placeholder="确认密码"
					:rules="rules.pwd2.bind(this)"
			/>
			<my-input
					v-model="form.nick"
					icon="icon-user1"
					placeholder="用户名"
			/>
			<my-input
					v-model="picCode"
					placeholder="图形验证码"
					:offRules="true"
			>
				<img :src="'https://api.it120.cc/small4/verification/pic/get?key='+picKey" @click="resetPicCode" alt="">
			</my-input>
			<div class="register-address">
				<h-selector v-model="address" :showValue="showAddress">
					<h-wrapper prop="province">
						<h-option v-for="item in provinceList" :key="item.id" :value="item.id">{{item.name}}</h-option>
					</h-wrapper>
					<h-wrapper prop="city">
						<h-option v-for="item in cityList" :key="item.id" :value="item.id">{{item.name}}</h-option>
					</h-wrapper>
				</h-selector>
			</div>
			<my-input class="register-code" v-model="form.code">
				<button @click="getMobileCode">获取验证码</button>
			</my-input>
			<div class="register-submit">
				<button @click="userRegister">立即注册</button>
			</div>
			<div class="register-login">
				<router-link to="/login">已有账号？ 立即登录</router-link>
			</div>
		</div>
	</div>
</template>

<script>
	import Address from '@/services/address';
	import User from '@/services/user';
	import {PHONE, PWD} from "@/utils/RegExp";
	import {mapActions} from 'vuex';
	import myInput from '#/Public/Input';

	const _address = new Address();
	const _user = new User();
	export default {
		name: "Register",
		data() {
			return {
				form: {
					nick: '',
					pwd: '',
					pwd2: '',
					mobile: '',
					code: ''
				},
				picCode: '',
				address: {
					province: '',
					city: ''
				},
				picKey: Date.now(),
				rules: {
					mobile(value) {
						return PHONE.test(value);
					},
					pwd(value) {
						return PWD.test(value);
					},
					pwd2(value) {
						return value === this.form.pwd;
					}
				},
				provinceList: [],
				cityList: []
			}
		},
		watch: {
			'address.province'(newValue) {
				this.getCity(newValue)
			}
		},
		computed: {
			showAddress() {
				let province = this.provinceList.find(item => item.id === this.address.province) || {name: '选择省'};
				let city = this.cityList.find(item => item.id === this.address.city) || {name: '选择市'};
				return `${province.name} - ${city.name}`;
			},
			addressName() {
				let province = this.provinceList.find(item => item.id === this.address.province) || {name: '未选择省'};
				let city = this.cityList.find(item => item.id === this.address.city) || {name: '未选择市'};
				return {
					province: province.name,
					city: city.name
				};
			}
		},
		methods: {
			...mapActions(['getUserDetail']),
			resetPicCode() {
				this.picKey = Date.now();
			},
			getProvince() {
				_address.getProvince().then(res => {
					this.provinceList = res.data;
				});
			},
			getCity(id) {
				_address.getCity(id).then(res => {
					this.address.city = '';
					this.cityList = res.data;
				}).catch(() => {
					this.cityList.splice(0);
				})
			},
			getMobileCode() {
				if (!this.validator()) {
					return;
				}
				let params = {
					mobile: this.form.mobile,
					key: this.picKey,
					picCode: this.picCode
				};
				_user.getMobileCode(params).then(res => {
					this.$message({
						type: 'success',
						message: '发送成功，请查收验证码！'
					})
				}).catch(err => {
					if (err.code === 502 || err.code === 501) {
						this.resetPicCode();
					}
				})
			},
			validator() {
				if (!this.rules.mobile(this.form.mobile)) {
					this.$message({
						type: 'error',
						message: '请填写正确的手机号码'
					});
					return false;
				} else if (!this.rules.pwd(this.form.pwd)) {
					this.$message({
						type: 'error',
						message: '请输入正确的密码格式'
					});
					return false;
				} else if (!this.rules.pwd(this.form.pwd2)) {
					this.$message({
						type: 'error',
						message: '两次输入的密码不一致'
					});
					return false;
				}
				return true;
			},
			userRegister() {
				if (!this.validator()) {
					return;
				}
				let params = Object.assign({}, this.form, this.addressName);
				_user.userRegister(params).then(res => {
					this.$message({
						type: 'success',
						message: '注册成功！为您自动登录'
					});
					let params = {
						mobile: this.form.mobile,
						pwd: this.form.pwd
					};
					_user.userLogin(params).then(res => {
						this.getUserDetail(res.data.token);
						let path = this.$route.query.redirect || '/';
						this.$router.push(path);
					})
				});
			}
		},
		created() {
			this.getProvince()
		},
		components: {
			myInput
		}
	}
</script>
